/*
 * @lc app=leetcode.cn id=1030 lang=typescript
 *
 * [1030] 距离顺序排列矩阵单元格
 */

// @lc code=start
function allCellsDistOrder(
    rows: number,
    cols: number,
    rCenter: number,
    cCenter: number
): number[][] {
    let queue: number[][] = [[rCenter, cCenter]];
    let final: number[][] = [];

    let cache = new Set<string>();
    while (queue.length) {
        const tag = queue[0].join(",");
        if (cache.has(tag)) {
            queue.shift();
            continue;
        }
        cache.add(tag);

        const [x, y] = queue[0];
        const around = [
            [x - 1, y],
            [x + 1, y],
            [x, y + 1],
            [x, y - 1],
        ].filter(([x, y]) => {
            return x >= 0 && x < rows && y >= 0 && y < cols;
        });
        queue.push(...around);
        final.push(queue.shift()!);
    }
    return final;
}
// @lc code=end
